#include "IQHello.h"
#include <python3.11/Python.h>
#include <stdexcept>

class PyIQImpl : public IQHello {
public:
    std::string getHello() override {
        PyObject *module = nullptr;
        PyObject *result = nullptr;
        std::string ret;

        PyObject *sysPath = PySys_GetObject("path");  // 获取当前 sys.path
        PyObject *path = PyUnicode_FromString("plugins");  // 替换为你的路径
        PyList_Append(sysPath, path);  // 添加到 sys.path

        try {
            module = PyImport_ImportModule("iq_impl");
            if (!module) {
                throw std::runtime_error("Failed to import module iq_impl");
            }
            
            result = PyObject_CallMethod(module, "get_hello", NULL);
            if (!result) {
                throw std::runtime_error("Failed to call get_hello");
            }
            
            if (!PyUnicode_Check(result)) {
                throw std::runtime_error("get_hello did not return a string");
            }
            
            const char* str = PyUnicode_AsUTF8(result);
            if (!str) {
                throw std::runtime_error("Failed to convert Python string to UTF-8");
            }
            
            ret = std::string(str);
        } catch (...) {
            Py_XDECREF(module);
            Py_XDECREF(result);
            throw;
        }
        
        Py_XDECREF(module);
        Py_XDECREF(result);
        return ret;
    }
};

extern "C" {

    IQImplType impl_t() {
        return IQ_IMPL_CPP;
    }

    DECLARE_CREATE_FUNC(IQHello) {
        if (!Py_IsInitialized()) {
            Py_Initialize();
        }
        return new PyIQImpl();
    }

    DECLARE_DELETE_FUNC(IQHello) {
        delete ptr;
    }
}